package com.guyaogg.gulimall.member.interceptor;

import com.guyaogg.common.constant.AuthServerConstant;
import com.guyaogg.common.vo.MemberRespVO;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 顾遥
 */
@Component
public class LoginUserInterceptor implements HandlerInterceptor {
    public static ThreadLocal<MemberRespVO> loginUser = new ThreadLocal<>();

    /**
     * 防止内存泄露，业务对象混乱，等等
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex) throws Exception {
        loginUser.remove();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        放行登录或注册入口 uri
        String uri = request.getRequestURI();
//        boolean register = new AntPathMatcher().match("/member/member/register", uri);
//        boolean login = new AntPathMatcher().match("/member/member/login", uri);
//        boolean oauth2 = new AntPathMatcher().match("/member/member/oauth2/**", uri);
//        boolean wareInfo = new AntPathMatcher().match("/member/member/memberreceiveaddress/info/**", uri);
                boolean member = new AntPathMatcher().match("/member/**", uri);

        if (member) {
            return true;
        }

        MemberRespVO attribute = (MemberRespVO) request.getSession().getAttribute(AuthServerConstant.LOGIN_USER);
        if (attribute != null) {
            loginUser.set(attribute);
            return true;
        } else {
            // 没登陆就去登录
            request.getSession().setAttribute("msg", "请先进行登录");
            response.sendRedirect("http://auth.gulimall.com/login.html");
            return false;
        }
    }
}
